import sublime
import sublime_plugin
import re

"""
	var(test) -> haha;
	var(test) ->>haha;
	haha;
"""

class DefineCommand(sublime_plugin.TextCommand):
	context = []

	def findVarAllFile(self, keyword):
		if len(self.context) == 0:
			return None
		for file in self.context:
			regex = re.compile(r"(?<=-\>\>) ?" + keyword)
			resultList = regex.finditer(file)
			if resultList != None:
				for res in resultList:
					# 判断是否是注释
					scopeInfo = self.view.scope_name(res.span()[0])
					if "comment" in scopeInfo:
						continue
					return res.span()

	def findFunAllFile(self, keyword):
		if len(self.context) == 0:
			return None
		for file in self.context:
			regex = re.compile(r"(?<=sub) ?" + keyword)
			resultList = regex.finditer(file)
			if resultList != None:
				for res in resultList:
					# 判断是否是注释
					scopeInfo = self.view.scope_name(res.span()[0])
					if "comment" in scopeInfo:
						continue
					return res.span()

	def isFunction(self, keywordLine):
		res = re.search(r"call", keywordLine)
		if res != None:
			return True
		else:
			return False

	def run(self, edit):
		# 获取所选取的关键字以及所在行数
		selectedReg = self.view.sel()[0]
		selPoint = selectedReg.begin()
		keywordReg = self.view.word(selPoint)
		keyword = self.view.substr(keywordReg)
		keywordLine = self.view.substr(self.view.line(selectedReg))

		# 记录sunlime中所有打开文件的上下文到context
		win = self.view.window()
		viewList = win.views()
		for view in viewList:
			self.context.append(view.substr(sublime.Region(0, view.size())))

		if self.isFunction(keywordLine) == False:
			index = self.findVarAllFile(keyword)
			if index != None:
				targetReg = sublime.Region(index[0], index[1])
				self.view.sel().clear()
				self.view.sel().add(targetReg)
				self.view.show_at_center(targetReg)
		elif self.isFunction(keywordLine) == True:
			index = self.findFunAllFile(keyword)
			if index != None:
				targetReg = sublime.Region(index[0], index[1])
				self.view.sel().clear()
				self.view.sel().add(targetReg)
				self.view.show_at_center(targetReg)

